package com.rd.config.security;

import cn.hutool.json.JSONUtil;
import com.rd.common.CommonResult;
import com.rd.util.JwtUtil;
import com.rd.util.ResultUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败处理器
 * 实现AuthenticationFailureHandler接口，并重写onAuthenticationFailure()方法；
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        //获取异常信息
        String message = exception.getMessage();
        CommonResult commonResult = ResultUtil.buildError(message);
        response.getWriter().write(JSONUtil.toJsonStr(commonResult));
    }
}
